using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using GridViewHelpr;
using ListMyHelper;
using Net.Http;
using NetCoreAudio;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using PddWebAuto.Helper;
using PddWebAuto.Model;
using PddWebAuto.PddModel;
using PddWebAuto.PddSearch;
using PddWebAuto.Properties;
using PddWebAuto.SmsHandler;
using PddWebAuto.ViewForm;
using Xml.SettingsXML;
using BorderStyle = NPOI.SS.UserModel.BorderStyle;

namespace PddWebAuto
{
    public partial class Frm : Form
    {
        private bool _ListPhoneIsEnd_;

        /// <summary>
        ///     订单导出数据存放路径
        /// </summary>
        private readonly string DataPath = "";

        /// <summary>
        /// 搜索服务
        /// </summary>
        private KeyWordSearchService _searchService;

        /// <summary>
        /// 当前浏览器所在分组
        /// </summary>
        public GroupModel CurrentGroup { get; set; }

        private GroupModel RunGroupModel;
        private readonly List<string> Task_SuccessUser = new List<string>();
        private readonly List<string> Task_FailUser = new List<string>();
        private ChromeDrive _chromeDrive;
        private List<ChromeDrive> _chromeDrives = new List<ChromeDrive>();

        /// <summary>
        ///     下单商品列表
        /// </summary>
        private DataGridHelpr ViewGrid_Goods = new DataGridHelpr();

        /// <summary>
        ///     组下项目表
        /// </summary>
        private ListHelper ViewList_Group;

        /// <summary>
        ///     短信手机号码验证表
        /// </summary>
        private ListHelper ViewList_Phone = new ListHelper();

        /// <summary>
        ///     批量退单商品列表
        /// </summary>
        private ListHelper ViewList_ReturnsGoods = new ListHelper();

        /// <summary>
        ///     上传单号列表
        /// </summary>
        private ListHelper ViewList_UpLogistics = new ListHelper();

        public Frm()
        {
            InitializeComponent();
            DataPath = Path.Combine(Application.StartupPath, "保存数据");
            Directory.CreateDirectory(DataPath);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Icon = Resources.a9gw7_5tcr9_001;

#if DEBUG
            button2.Visible = true;
#endif

            SettingsStatic.Settings = new SettingsXML("setting.xml");
            openFileDialog1.Filter = @"表格|*.xlsx|文本|*.txt";
            openFileDialog1.Multiselect = false;

            ViewList_Group = new ListHelper(listView1);
            ViewGrid_Goods = new DataGridHelpr(dataGridView1);
            ViewList_Phone = new ListHelper(listView2);
            ViewList_ReturnsGoods = new ListHelper(listView3);
            ViewList_UpLogistics = new ListHelper(listView4);
            ReGroupList();
            SaveSettings(false);
            contextMenuStripMouveGroup.ItemClicked += ContextMenuStrip2_ItemClicked;
        }

        private void IpProxyManage_ProxyError(string obj)
        {
            if (Program._Run_ == 1 && !obj.Contains("API提取异常"))
            {
                Program._Run_ = -1;
            }

            Log("代理报错:" + obj);
        }

        private bool CheckProxyCall(string IP)
        {
            var item = new HttpItem();
            item.Method = "GET";
            item.URL = "https://mobile.yangkeduo.com/";
            item.ProxyIp = IP;
            item.Timeout = 4 * 1000;
            item.ReadWriteTimeout = 4 * 1000;
            var _startTime = DateTime.Now;
            var Res = item.Send();
            var TotalMilliseconds = (DateTime.Now - _startTime).TotalMilliseconds;
            if (Res.IsSuccessStatusCode)
            {
                if (Res.Html.Contains("拼多多商城"))
                {
                    Debug.WriteLine(TotalMilliseconds);
                    return TotalMilliseconds <= int.Parse(textBox17.Text);
                }

                return false;
            }

            return false;
        }

        private void SaveSettings(bool IsSave)
        {
            if (IsSave)
            {
                SettingsStatic.Settings.SetValue("EnableAlipayLogin", checkBox2.Checked);
                SettingsStatic.Settings.SetValue("CheckExistOrder", checkBox1.Checked);
                SettingsStatic.Settings.SetValue("ClosePddWallet", checkBox37.Checked);

                SettingsStatic.Settings.SetValue("WebApiUrl", textBox10.Text);
                SettingsStatic.Settings.SetValue("ChromePath", textBox4.Text);
                SettingsStatic.Settings.SetValue("AlipayUser", textBox6.Text);
                SettingsStatic.Settings.SetValue("SmsPlatform", radioButton1.Checked);
                SettingsStatic.Settings.SetValue("SmsApiUser", textBox15.Text);
                SettingsStatic.Settings.SetValue("SmsApiPass", textBox16.Text);
                //搜索配置
                SettingsStatic.Settings.SetValue("PddSearchNum", textBox3.Text);
                SettingsStatic.Settings.SetValue("PddSearchWheelStart", textBox14.Text);
                SettingsStatic.Settings.SetValue("PddSearchWheelEnd", textBox11.Text);
                SettingsStatic.Settings.SetValue("PddSearchWheelSleepStart", textBox13.Text);
                SettingsStatic.Settings.SetValue("PddSearchWheelSleepEnd", textBox12.Text);

                SettingsStatic.Settings.SetValue("ProxySpeed", textBox17.Text);

                SettingsStatic.Settings.Save();
            }
            else
            {
                checkBox2.Checked = SettingsStatic.Settings.GetValue<bool>("EnableAlipayLogin", false);
                radioButton1.Checked = SettingsStatic.Settings.GetValue<bool>("SmsPlatform", true);
                radioButton2.Checked = !radioButton1.Checked;
                checkBox1.Checked = SettingsStatic.Settings.GetValue<bool>("CheckExistOrder", false);
                checkBox37.Checked = SettingsStatic.Settings.GetValue<bool>("ClosePddWallet", false);

                textBox6.Text = SettingsStatic.Settings.GetValue<string>("AlipayUser", "");
                textBox10.Text = SettingsStatic.Settings.GetValue<string>("WebApiUrl", "");
                textBox4.Text = SettingsStatic.Settings.GetValue<string>("ChromePath", "");
                textBox15.Text = SettingsStatic.Settings.GetValue<string>("SmsApiUser", "");
                textBox16.Text = SettingsStatic.Settings.GetValue<string>("SmsApiPass", "");

                textBox3.Text = SettingsStatic.Settings.GetValue<string>("PddSearchNum", "30");
                textBox14.Text = SettingsStatic.Settings.GetValue<string>("PddSearchWheelStart", "40");
                textBox11.Text = SettingsStatic.Settings.GetValue<string>("PddSearchWheelEnd", "150");
                textBox13.Text = SettingsStatic.Settings.GetValue<string>("PddSearchWheelSleepStart", "1000");
                textBox12.Text = SettingsStatic.Settings.GetValue<string>("PddSearchWheelSleepEnd", "3000");
                textBox17.Text = SettingsStatic.Settings.GetValue<string>("ProxySpeed", "900");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Program._Run_ == 0)
            {
                Task_SuccessUser.Clear();
                Task_FailUser.Clear();
                if (string.IsNullOrEmpty(textBox4.Text))
                {
                    Log("指纹浏览器目录为设置!");
                    return;
                }

                if (GetActivityGroup() != null)
                {
                    panel1.Enabled = false;
                    button1.Text = "停止任务";
                    if (Program.CancellationTokenSource.IsCancellationRequested)
                    {
                        Program.CancellationTokenSource = new CancellationTokenSource();
                    }

                    Program._Run_ = 1;
                    Task.Run(async () =>
                    {
                        try
                        {
                            var cancel =
                                CancellationTokenSource.CreateLinkedTokenSource(Program.CancellationTokenSource.Token);
                            await StartTask(cancel.Token);
                        }
                        catch (Exception ex)
                        {
                            Log("StartTask Try:" + ex.Message);
                        }

                        Log("<<<任务结束");
                        if (Task_SuccessUser.Count > 0 || Task_FailUser.Count > 0)
                        {
                            if (Task_FailUser.Count > 0)
                            {
                                foreach (var item in Task_FailUser)
                                {
                                    Log("[失败] " + item);
                                }
                            }

                            Log("浏览器报告 成功:" + Task_SuccessUser.Count + " 失败:" +
                                Task_FailUser.Count);
                        }

                        Program._Run_ = 0;
                        Invoke(new Action(() =>
                        {
                            button1.Text = "启动任务";
                            panel1.Enabled = true;
                            button1.Enabled = true;
                        }));
                    });
                }
            }
            else
            {
                if (Program._Run_ == 1)
                {
                    Program._Run_ = -1;
                    try
                    {
                        Program.CancellationTokenSource.Cancel();
                    }
                    catch (Exception)
                    {
                        // ignored
                    }

                    Task.Run(async () =>
                    {
                        await Task.Delay(1500);
                        Program.CancellationTokenSource = new CancellationTokenSource();
                    });
                    button1.Enabled = false;
                }
            }
        }

        private Dictionary<string, object> GetGoodsCheckedRow()
        {
            while (ViewGrid_Goods.ExistNext())
            {
                var m = ViewGrid_Goods.Next();
                if ((bool)m["选"])
                {
                    return m;
                }
            }

            return null;
        }

        /// <summary>
        ///     通过组启动项目浏览器
        /// </summary>
        /// <param name="Call"></param>
        /// <param name="IsChecked"></param>
        /// <returns></returns>
        private async Task GroupSatrtItemChrome(Func<int, ChromeDrive, Task<bool>> Call, GroupModel group,
            bool IsChecked = true)
        {
            for (var i = 0; i < ViewList_Group.GetCount(); i++)
            {
                if (Program._Run_ != 1)
                {
                    break;
                }

                if (!IsChecked || ViewList_Group.IsChecked(i)) //检测选中
                {
                    var m = (GroupItemModel)ViewList_Group.GetDataTag(i);
                    var Chrome = new ChromeDrive(Log, group);
                    try
                    {
                        var proxy = string.Empty;
                        if (group?.UseProxy == true)
                        {
                            var proxies = group.ProxyUrl.Split(",".ToCharArray(),
                                StringSplitOptions.RemoveEmptyEntries);
                            if (proxies.Length == 1)
                            {
                                proxy = proxies[0];
                            }
                            else
                            {
                                if (proxies.Length <= i)
                                {
                                    Log("分组中的代理数量不足");
                                    return;
                                }

                                proxy = proxies[i];
                            }

                            if (proxy.Contains(":"))
                            {
                                Log($"正在刷新代理IP:{proxy}");

                                //刷新下代理
                                await TunnelProxiesHelper.RefreshProxyAsync(proxy.Split(":".ToCharArray(),
                                    StringSplitOptions.RemoveEmptyEntries)[1]);
                            }
                        }

                        if (await Chrome.RunChromeProcessAsync(m, proxy,
                                group?.UseProxy ?? false))
                        {
                            if (!await Call.Invoke(i, Chrome))
                            {
                                break;
                            }
                        }
                    }
                    catch (TaskCanceledException)
                    {
                        SetTaskSuccessFail(i, false);
                    }
                    catch (Exception ex)
                    {
                        SetTaskSuccessFail(i, false);
                        Log("Try:" + ex.Message);
                    }
                    finally
                    {
                        Chrome.Dispose();
                    }
                }
            }
        }

        private async Task StartTask(CancellationToken token)
        {
            token.Register(() => throw new TaskCanceledException());

            ViewGrid_Goods.BeginNext();
            var GroupName = GetActivityGroup();
            RunGroupModel = AppClass.Get_GroupModel(GroupName);
            var TaskType = (string)Invoke(new Func<string>(() => { return comboBox3.Text; }));
            Log("开始任务>>>> 目标组:" + GroupName + " 任务:" + TaskType);
            if (TaskType == "登陆账户")
            {
                await Task_Login(RunGroupModel);
            }
            else if (TaskType == "下单")
            {
                await Task_DownOrder(RunGroupModel);
            }
            else if (TaskType == "导出订单")
            {
                await Task_OrderExport(RunGroupModel);
            }
            else if (TaskType == "导出售后")
            {
                await Task_AfterSaleOrder(RunGroupModel);
            }
            else if (TaskType == "批量退款" || TaskType == "上传单号")
            {
                //匹配类型任务
                await StartMatchTask(TaskType, RunGroupModel);
            }
            else if (TaskType == "采集列表商品")
            {
                this._chromeDrives.RemoveAll(x => x.ChromeProcess?.HasExited == true);
                if (this._chromeDrives == null || this._chromeDrives.Count == 0)
                {
                    MessageBox.Show(@"请启动浏览器后再操作~");
                    return;
                }

                var drivers = this._chromeDrives.Where(x => x.Group.Title == RunGroupModel.Title &&
                                                            x.ChromeProcess != null && !x.ChromeProcess.HasExited)
                    .ToList();
                if (drivers.Count == 0)
                {
                    MessageBox.Show(@"请启动浏览器后再操作~");
                    return;
                }

                if (drivers.Count == 1)
                {
                    MessageBox.Show(@"打开的浏览器数量不足~");
                    return;
                }

                var searchDriver =
                    drivers.FirstOrDefault(x => x._currentPage?.Url?.Contains("search_result.html") == true);
                if (searchDriver == null)
                {
                    MessageBox.Show(@"请在任意浏览器搜索关键字~");
                    return;
                }

                //其他负责搜索详情页的浏览器
                var detailDrivers = drivers.Where(x => x.Group.Title == searchDriver.Group.Title && x != searchDriver)
                    .ToList();
                var searchSetting = new SearchSettingModel();
                Invoke(new Action(() =>
                {
                    searchSetting.FilterTag = PanelFilterGetHandle(groupBox2);
                    searchSetting.MaxSearchNum = int.Parse(textBox3.Text);
                    searchSetting.WheelStartL = int.Parse(textBox14.Text);
                    searchSetting.WheelEndL = int.Parse(textBox11.Text);
                    searchSetting.WheelStartSleep = int.Parse(textBox13.Text);
                    searchSetting.WheelEndSleep = int.Parse(textBox12.Text);
                    searchSetting.Group = RunGroupModel;
                    searchSetting.BfSearch = checkBox3.Checked;
                    searchSetting.SetStatusLabel = CJ_SetStatusLabel;
                }));
                _searchService = new KeyWordSearchService(searchDriver, detailDrivers, searchSetting, Log);

                var cancel = CancellationTokenSource.CreateLinkedTokenSource(Program.CancellationTokenSource.Token);

                Task.Run(SearchParamterUpdateAsync, cancel.Token);

                //运行
                await _searchService.RunAsync();
            }
        }

        /// <summary>
        /// 每2秒更新一次搜索参数
        /// </summary>
        private async void SearchParamterUpdateAsync()
        {
            try
            {
                while (_searchService != null && Program._Run_ == 1)
                {
                    try
                    {
                        Invoke(new Action(() =>
                        {
                            try
                            {
                                _searchService.Setting.FilterTag = PanelFilterGetHandle(groupBox2);
                                _searchService.Setting.MaxSearchNum = int.Parse(textBox3.Text);
                                _searchService.Setting.WheelStartL = int.Parse(textBox14.Text);
                                _searchService.Setting.WheelEndL = int.Parse(textBox11.Text);
                                _searchService.Setting.WheelStartSleep = int.Parse(textBox13.Text);
                                _searchService.Setting.WheelEndSleep = int.Parse(textBox12.Text);
                                _searchService.Setting.BfSearch = checkBox3.Checked;
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }));
                    }
                    catch (Exception e)
                    {
                        // ignored
                    }
                    finally
                    {
                        await TaskHelper.Delay(2000);
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }


        /// <summary>
        ///     获取组面板选中的项目标题
        /// </summary>
        /// <param name="Box"></param>
        /// <returns></returns>
        private static List<string> PanelFilterGetHandle(GroupBox Box)
        {
            var Filters = new List<string>();
            foreach (var Control in Box.Controls)
            {
                switch (Control)
                {
                    case CheckBox Check when Check.Checked:
                        Filters.Add(Check.Text);
                        break;
                    case RadioButton Check2 when Check2.Checked:
                        Filters.Add(Check2.Text);
                        break;
                }
            }

            return Filters;
        }

        /// <summary>
        ///     浏览器Key获取对应项目
        /// </summary>
        /// <param name="BrowserKey"></param>
        /// <returns></returns>
        private int BrowserMatchGroupItem(string BrowserKey)
        {
            var key = BrowserKey.Split('-');
            string BKey = null;
            string BName = null;
            if (key.Length == 3)
            {
                BName = key[1].Trim();
                BKey = key[2].Trim();
            }
            else if (key.Length == 2)
            {
                BName = key[0].Trim();
                BKey = key[1].Trim();
            }
            else if (key.Length == 1)
            {
                BName = key[0].Trim();
            }

            for (var i = 0; i < ViewList_Group.GetCount(); i++)
            {
                var ItemName = ViewList_Group.GetItemString(i, "浏览器名称").Trim();
                var ItemFileName = ViewList_Group.GetItemString(i, "FileName").Trim();
                if (BName == ItemName || ItemFileName == BKey)
                {
                    return i;
                }
            }

            return -1;
        }

        /// <summary>
        ///     启动查找浏览器匹配任务
        /// </summary>
        /// <param name="TaskType"></param>
        /// <returns></returns>
        private async Task StartMatchTask(string TaskType, GroupModel group)
        {
            ListHelper ListView = null;
            if (TaskType == "批量退款")
            {
                ListView = ViewList_ReturnsGoods;
            }
            else if (TaskType == "上传单号")
            {
                ListView = ViewList_UpLogistics;
            }

            await ListView.ForItemsAsync(async (index, values) =>
            {
                GroupItemModel Item = null;
                var Index = BrowserMatchGroupItem(values["浏览器"]);
                if (Index > -1)
                {
                    Item = (GroupItemModel)ViewList_Group.GetDataTag(Index);
                }
                else
                {
                    Log("ID:" + values["ID"] + " 找不到对应浏览器:" + values["浏览器"]);
                }

                if (Item != null)
                {
                    var proxy = string.Empty;
                    if (group?.UseProxy == true)
                    {
                        var proxies = group.ProxyUrl.Split(",".ToCharArray(),
                            StringSplitOptions.RemoveEmptyEntries);
                        if (proxies.Length == 1)
                        {
                            proxy = proxies[0];
                        }
                        else
                        {
                            if (proxies.Length <= index)
                            {
                                Log("分组中的代理数量不足");
                                return default;
                            }

                            proxy = proxies[index];
                        }

                        Log($"正在刷新代理IP:{proxy}");

                        //刷新下代理
                        await TunnelProxiesHelper.RefreshProxyAsync(proxy.Split(":".ToCharArray(),
                            StringSplitOptions.RemoveEmptyEntries)[1]);
                    }

                    var Chrome = new ChromeDrive(Log, group);
                    if (await Chrome.RunChromeProcessAsync(Item, proxy,
                            group?.UseProxy ?? false))
                    {
                        if (TaskType == "批量退款")
                        {
                            if (await Task_ReturnsGoods(index, Chrome))
                            {
                                SetTaskSuccessFail(index, true);
                            }
                            else
                            {
                                SetTaskSuccessFail(index, false);
                            }
                        }
                        else if (TaskType == "上传单号")
                        {
                            if (await Task_UploadOrderTracking(index, Chrome))
                            {
                                SetTaskSuccessFail(index, true);
                            }
                            else
                            {
                                SetTaskSuccessFail(index, false);
                            }
                        }
                    }

                    Chrome.Dispose();
                }

                return Program._Run_ == 1;
            }, CheckedState: true);
        }

        /// <summary>
        ///     获取导入短信列表
        /// </summary>
        /// <returns></returns>
        private string[] GetListPhone()
        {
            var GetCount = ViewList_Phone.GetCount();
            if (GetCount > 0)
            {
                for (var i = 0; i < GetCount; i++)
                {
                    if (string.IsNullOrEmpty(ViewList_Phone.GetItemString(i, "状态")))
                    {
                        var COM = ViewList_Phone.GetItemString(i, "COM");
                        var Phone = ViewList_Phone.GetItemString(i, "手机号");
                        ViewList_Phone.UpdateText(i, "状态", "使用中");
                        if (i == GetCount - 1)
                        {
                            _ListPhoneIsEnd_ = true;
                        }

                        return new string[3] { COM, Phone, i.ToString() };
                    }
                }
            }

            _ListPhoneIsEnd_ = true;
            return null;
        }

        /// <summary>
        ///     统计浏览器的成功跟失败
        /// </summary>
        /// <param name="Index"></param>
        /// <param name="IsSuccess"></param>
        private void SetTaskSuccessFail(int Index, bool IsSuccess)
        {
            var Title = ((GroupItemModel)ViewList_Group.GetDataTag(Index)).Title;
            if (IsSuccess)
            {
                Task_SuccessUser.Add(Title);
            }
            else
            {
                Task_FailUser.Add(Title);
            }
        }

        private void Log(string t)
        {
            Invoke(new Action(() =>
            {
                try
                {
                    Program.Logger.Debug(t);
                    textBox2.AppendText(t + "\r\n");
                }
                catch (Exception)
                {
                }
            }));
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (GetActivityGroup() != null)
            {
                if (MessageBox.Show("确认删除?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    var Name = GetActivityGroup();
                    if (AppClass.Del_Group(Name))
                    {
                        comboBox1.Items.Remove(Name);
                        ReGroupItemViewList();
                    }
                    else
                    {
                        MessageBox.Show("有文件被占用无法完整删除!");
                    }
                }
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            var F = new FormNewGroup(null);

            if (F.ShowDialog(this) == DialogResult.OK)
            {
                if (AppClass.CreateGroupSub(F.GroupInfo))
                {
                    ReGroupList();
                }
                else
                {
                    MessageBox.Show("创建组失败,请检查是否已存在!");
                }
            }
        }

        /// <summary>
        ///     获取当前激活的组 未选中会返回Null
        /// </summary>
        /// <returns></returns>
        private string GetActivityGroup()
        {
            return (string)Invoke(new Func<string>(() =>
            {
                if (comboBox1.SelectedIndex > -1)
                {
                    if (!string.IsNullOrEmpty(comboBox1.Text))
                    {
                        return comboBox1.Text;
                    }
                }
                return null;
            }));
        }

        /// <summary>
        ///     刷新组列表
        /// </summary>
        private void ReGroupList()
        {
            comboBox1.Items.Clear();
            var AllGroup = AppClass.GetAllGroup().ToArray();
            comboBox1.Items.AddRange(AllGroup);
        }

        /// <summary>
        ///     刷新组下列表显示
        /// </summary>
        private void ReGroupItemViewList()
        {
            ViewList_Group.Clear();
            if (GetActivityGroup() != null)
            {
                var GroupName = GetActivityGroup();
                listView1.Tag = false;
                foreach (var item in AppClass.GetGroupAllItem(GroupName))
                {
                    var X = ViewList_Group.AddItems(title =>
                    {
                        if (title == "ID")
                        {
                            return (ViewList_Group.GetCount() + 1).ToString();
                        }

                        if (title == "浏览器名称")
                        {
                            return item.Value.Title;
                        }

                        if (title == "备注")
                        {
                            return item.Value.Des;
                        }

                        if (title == "创建时间")
                        {
                            return item.Value.CreateTime.ToString();
                        }

                        if (title == "FileName")
                        {
                            return item.Key;
                        }

                        if (title == "GroupName")
                        {
                            return GroupName;
                        }

                        return "";
                    }, i =>
                    {
                        i.Checked = item.Value.Enable;
                        i.Tag = item.Value;
                    });
                }
            }
        }

        /// <summary>
        ///     刷新项目列表自身显示
        /// </summary>
        /// <param name="Index"></param>
        private void ReItemModelDisplay(int Index)
        {
            var m = ViewList_Group.GetDataTag(Index) as GroupItemModel;
            if (m != null)
            {
                ViewList_Group.UpdateText(Index, "备注", m.Des);
                ViewList_Group.UpdateText(Index, "浏览器名称", m.Title);
            }
        }

        /// <summary>
        ///     更新列表项目模型
        /// </summary>
        /// <param name="Index"></param>
        /// <param name="Fun"></param>
        /// <param name="Save"></param>
        /// <param name="ReDisplay"></param>
        private void UpItemModel(int Index, Action<GroupItemModel> Fun, bool Save = true, bool ReDisplay = true)
        {
            var GroupName = ViewList_Group.GetItemString(Index, "GroupName");
            var FileName = ViewList_Group.GetItemString(Index, "FileName");
            if (!string.IsNullOrEmpty(GroupName) && !string.IsNullOrEmpty(FileName))
            {
                var m = ViewList_Group.GetDataTag(Index) as GroupItemModel;
                if (m != null)
                {
                    Fun.Invoke(m);
                    ViewList_Group.SetDataTag(Index, m);
                    if (ReDisplay)
                    {
                        ReItemModelDisplay(Index);
                    }

                    if (Save)
                    {
                        AppClass.Save_GroupItem(m, GroupName, FileName);
                    }
                }
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            ReGroupList();
            ReGroupItemViewList();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ReGroupItemViewList();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (GetActivityGroup() != null)
            {
                var Name = GetActivityGroup();
                var f = new FormChromeOptions(new GroupItemModel());
                if (f.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (var item in f.ItemModelList)
                    {
                        item.CreateTime = DateTime.Now;
                        //保持一致用浏览器名称 创建对应的项目名称
                        var FileName = AppClass.Save_GroupItem(item, Name, item.ChromeData);
                        if (FileName == null)
                        {
                            Log("新建出错:" + item.Title);
                        }
                    }

                    ReGroupItemViewList();
                }
            }
        }

        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == 0)
            {
                if (ViewList_Group.GetCount() > 0)
                {
                    listView1.Tag = !(bool)listView1.Tag;
                    ViewList_Group.SetAllCheckState((bool)listView1.Tag ? 1 : 0);
                }
            }
        }

        private void contextMenuStrip2_Opening(object sender, CancelEventArgs e)
        {
            contextMenuStripMouveGroup.Items.Clear();
            if (ViewList_Group.GetSelectedItemFirstIndex() > -1)
            {
                var GroupName = ViewList_Group.GetSelectedItemString("GroupName");
                foreach (var item in AppClass.GetAllGroup().ToArray())
                {
                    if (item != GroupName)
                    {
                        contextMenuStripMouveGroup.Items.Add(item);
                    }
                }
            }
        }

        private void ContextMenuStrip2_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (ViewList_Group.GetSelectedItemFirstIndex() > -1)
            {
                var FileName = ViewList_Group.GetSelectedItemString("FileName");
                var GroupName = ViewList_Group.GetSelectedItemString("GroupName");
                var MenuItem = contextMenuStripMouveGroup.OwnerItem;
                if (MenuItem.Text.Contains("打勾"))
                {
                    ViewList_Group.ForItems((index, nv) =>
                    {
                        AppClass.Move_GroupItem(GroupName, e.ClickedItem.Text, nv["FileName"]);
                        return true;
                    }, CheckedState: true);
                }
                else
                {
                    AppClass.Move_GroupItem(GroupName, e.ClickedItem.Text, FileName);
                }

                ReGroupItemViewList();
            }
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            if (ViewList_Group.GetSelectedItemFirstIndex() > -1)
            {
                var Index = ViewList_Group.GetSelectedItemFirstIndex();
                var FileName = ViewList_Group.GetSelectedItemString("FileName");
                var GroupName = ViewList_Group.GetSelectedItemString("GroupName");
                if (AppClass.Del_GroupItem(GroupName, FileName))
                {
                    ViewList_Group.RemoveItems(Index);
                }
            }
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (ViewList_Group.GetSelectedItemFirstIndex() > -1)
            {
                Task.Run(async () =>
                {
                    var Index = ViewList_Group.GetSelectedItemFirstIndex();
                    var PID = ViewList_Group.GetItemString(Index, "PID");
                    if (!string.IsNullOrEmpty(PID))
                    {
                        try
                        {
                            var p = Process.GetProcessById(int.Parse(PID));
                            Log("浏览器窗口已打开");
                            return;
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }

                    var GroupModel = AppClass.Get_GroupModel(GetActivityGroup());
                    var chromeDrive =
                        await RunSingleItemChrome(GroupModel, Index, (GroupItemModel)ViewList_Group.GetDataTag(Index));
                    if (chromeDrive != null)
                    {
                        ViewList_Group.UpdateText(Index, "PID", chromeDrive.ChromeProcess.Id.ToString());
                        _chromeDrive = chromeDrive;
                        //移除离线的
                        this._chromeDrives.RemoveAll(x => x.ChromeProcess?.HasExited == true);
                        _chromeDrives.Add(chromeDrive);
                    }
                });
            }
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            if (GetActivityGroup() != null)
            {
                for (var i = 0; i < ViewList_Group.GetCount(); i++)
                {
                    var FileName = ViewList_Group.GetItemString(i, "FileName");
                    var GroupName = ViewList_Group.GetItemString(i, "GroupName");
                    var m = (GroupItemModel)ViewList_Group.GetDataTag(i);
                    m.Enable = ViewList_Group.IsChecked(i);
                    AppClass.Save_GroupItem(m, GroupName, FileName);
                }
            }
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            if (ViewList_Group.GetSelectedItemFirstIndex() > -1)
            {
                var Index = ViewList_Group.GetSelectedItemFirstIndex();
                var FileName = ViewList_Group.GetSelectedItemString("FileName");
                var GroupName = ViewList_Group.GetSelectedItemString("GroupName");
                var f = new FormChromeOptions((GroupItemModel)ViewList_Group.GetDataTag(Index), true);
                if (f.ShowDialog(this) == DialogResult.OK)
                {
                    if (AppClass.Save_GroupItem(f.ItemModelList[0], GroupName, FileName) != null)
                    {
                        ReGroupItemViewList();
                    }
                    else
                    {
                        MessageBox.Show("编辑浏览器失败!");
                    }
                }
            }
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = "";
            openFileDialog1.FilterIndex = 1;
            if (openFileDialog1.ShowDialog() != DialogResult.OK ||
                string.IsNullOrWhiteSpace(openFileDialog1.FileName))
            {
                return;
            }

            IWorkbook workbook = default;
            if (Path.GetExtension(new FileInfo(openFileDialog1.FileName).Name) == @".xls")
            {
                workbook = new HSSFWorkbook(new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read,
                    FileShare.Read));
            }
            else if (Path.GetExtension(new FileInfo(openFileDialog1.FileName).Name) == @".xlsx")
            {
                workbook = new XSSFWorkbook(openFileDialog1.FileName);
            }
            else
            {
                MessageBox.Show(@"选择的文件格式不正确~,必须是*.xls|*.xlsx");
                return;
            }

            var sheet = workbook.GetSheetAt(0);
            ViewGrid_Goods.RowClear();
            for (var i = 1; i < sheet.LastRowNum + 1; i++)
            {
                var row = sheet.GetRow(i);
                if (string.IsNullOrEmpty(ExcelHelper.GetCellValue(row.GetCell(0))))
                {
                    continue;
                }

                var cellNum = row.LastCellNum;
                JArray jArray = default;
                ViewGrid_Goods.AddRow((title, type) =>
                {
                    switch (title)
                    {
                        case "选":
                            return false;
                        case "商品ID":
                            return "https://mobile.yangkeduo.com/goods.html?goods_id=" +
                                   ExcelHelper.GetCellValue(row.GetCell(0));
                        case "商品名称":
                            return ExcelHelper.GetCellValue(row.GetCell(1));
                        case "商品价格":
                            return ExcelHelper.GetCellValue(row.GetCell(2));
                        case "店铺名称":
                            return ExcelHelper.GetCellValue(row.GetCell(3));
                        case "下单Sku":
                        {
                            var Sku = ExcelHelper.GetCellValue(row.GetCell(9));
                            try
                            {
                                var skus = new List<string>();
                                jArray = JArray.Parse(Sku);
                                for (var x = 0; x < jArray.Count; x++)
                                {
                                    if (!(jArray[x]["skus"] is JArray skusJa))
                                    {
                                        continue;
                                    }

                                    if ((int)jArray[x]["quantity"] > 0)
                                    {
                                        skus.Add("[" + (x + 1) + "]" +
                                                 string.Join("/", skusJa.Select(s => (string)s).ToArray()) +
                                                 "  " + (string)jArray[x]["price"] + "/" +
                                                 (string)jArray[x]["quantity"]);
                                    }
                                }

                                return skus;
                            }
                            catch (Exception)
                            {
                                // ignored
                            }

                            break;
                        }
                        case "收货人":
                            return cellNum >= 10 ? ExcelHelper.GetCellValue(row.GetCell(10))?.Trim() : "";
                        case "电话":
                            return cellNum >= 11 ? ExcelHelper.GetCellValue(row.GetCell(11))?.Trim() : "";
                        case "省":
                            return cellNum >= 12 ? ExcelHelper.GetCellValue(row.GetCell(12))?.Trim() : "";
                        case "市":
                            return cellNum >= 13 ? ExcelHelper.GetCellValue(row.GetCell(13))?.Trim() : "";
                        case "区":
                            return cellNum >= 14 ? ExcelHelper.GetCellValue(row.GetCell(14))?.Trim() : "";
                        case "详细地址":
                            return cellNum >= 15 ? ExcelHelper.GetCellValue(row.GetCell(15))?.Trim() : "";
                        case "ID":
                            return ViewGrid_Goods.Count() + 1;
                        case DataGridHelpr._RowData_:
                            return jArray;
                    }

                    return null;
                });
            }

            workbook.Dispose();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > -1)
            {
                if (e.RowIndex > -1)
                {
                    if (ViewGrid_Goods.GetColIndex("选") == e.ColumnIndex)
                    {
                        ViewGrid_Goods.SetValue("选", e.RowIndex, !(bool)ViewGrid_Goods.GetValue("选", e.RowIndex));
                    }
                    else if (ViewGrid_Goods.GetColIndex("下单Sku") == e.ColumnIndex)
                    {
                        dataGridView1.BeginEdit(false);
                        ((ComboBox)dataGridView1.EditingControl).DroppedDown = true;
                    }
                }
                else
                {
                    //表头点击
                    if (ViewGrid_Goods.GetColIndex("选") == e.ColumnIndex)
                    {
                        var State = ViewGrid_Goods.GetColData(e.ColumnIndex) ?? false;
                        ViewGrid_Goods.SetAllCheckState("选", (bool)State ? 0 : 1);
                        ViewGrid_Goods.SetColData(e.ColumnIndex, !(bool)State);
                    }
                }
            }
        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (ViewGrid_Goods.GetColIndex("选") == e.ColumnIndex ||
                ViewGrid_Goods.GetColIndex("下单Sku") == e.ColumnIndex)
            {
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = "";
            openFileDialog1.FilterIndex = 2;

            if (openFileDialog1.ShowDialog() != DialogResult.OK ||
                string.IsNullOrWhiteSpace(openFileDialog1.FileName))
            {
                return;
            }

            ViewList_Phone.Clear();
            foreach (var item in File.ReadAllLines(openFileDialog1.FileName))
            {
                var array = item.Split(',');
                if (array.Length == 2)
                {
                    ViewList_Phone.AddItems(title =>
                    {
                        switch (title)
                        {
                            case "COM":
                                return array[0].Replace("COM", "");
                            case "手机号":
                                return array[1];
                            case "ID":
                                return (ViewList_Phone.GetCount() + 1).ToString();
                            default:
                                return null;
                        }
                    });
                }
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            SaveSettings(true);
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            ChromeDrive.ChromePath = textBox4.Text;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Task.Run(async () => { await _chromeDrive.OrderExportTask(); });
        }

        private void toolStripMenuItem10_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = string.Empty;
            if (openFileDialog1.ShowDialog() != DialogResult.OK ||
                string.IsNullOrWhiteSpace(openFileDialog1.FileName))
            {
                return;
            }

            IWorkbook workbook = default;
            if (Path.GetExtension(new FileInfo(openFileDialog1.FileName).Name) == @".xls")
            {
                workbook = new HSSFWorkbook(new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read,
                    FileShare.Read));
            }
            else if (Path.GetExtension(new FileInfo(openFileDialog1.FileName).Name) == @".xlsx")
            {
                workbook = new XSSFWorkbook(openFileDialog1.FileName);
            }
            else
            {
                MessageBox.Show(@"选择的文件格式不正确~,必须是*.xls|*.xlsx");
                return;
            }

            var sheet = workbook.GetSheetAt(0);
            ViewList_ReturnsGoods.Clear();
            var browserIndex = GetExcelColumnIndex(sheet, "浏览器");
            var orderIndex = GetExcelColumnIndex(sheet, "订单编号");
            if (browserIndex == -1 || orderIndex == -1)
            {
                MessageBox.Show(@"表格缺少必备列 浏览器,订单编号");
                return;
            }

            for (var i = 1; i < sheet.LastRowNum + 1; i++)
            {
                var row = sheet.GetRow(i);
                ViewList_ReturnsGoods.AddItems(title =>
                {
                    switch (title)
                    {
                        case "ID":
                            return (ViewList_ReturnsGoods.GetCount() + 1).ToString();
                        case "浏览器":
                        case "订单编号":
                            return ExcelHelper.GetCellValue(row.GetCell(title == @"浏览器" ? browserIndex : orderIndex));
                    }

                    return null;
                });
            }

            workbook.Dispose();
        }

        /// <summary>
        ///     获取指定表格列的index
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="ColName"></param>
        /// <returns></returns>
        private int GetExcelColumnIndex(ISheet sheet, string ColName)
        {
            if (sheet.LastRowNum <= 0)
            {
                return -1;
            }

            for (var i = 0; i < sheet.LastRowNum + 1; i++)
            {
                var row = sheet.GetRow(i);
                if (row.LastCellNum < 0)
                {
                    continue;
                }

                for (var j = 0; j < row.LastCellNum + 1; j++)
                {
                    if (ExcelHelper.GetCellValue(row.GetCell(j)) == ColName)
                    {
                        return j;
                    }
                }
            }

            return -1;
        }

        private void toolStripMenuItem11_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = string.Empty;
            if (openFileDialog1.ShowDialog() != DialogResult.OK ||
                string.IsNullOrWhiteSpace(openFileDialog1.FileName))
            {
                return;
            }

            IWorkbook workbook = default;
            if (Path.GetExtension(new FileInfo(openFileDialog1.FileName).Name) == @".xls")
            {
                workbook = new HSSFWorkbook(new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read,
                    FileShare.Read));
            }
            else if (Path.GetExtension(new FileInfo(openFileDialog1.FileName).Name) == @".xlsx")
            {
                workbook = new XSSFWorkbook(openFileDialog1.FileName);
            }
            else
            {
                MessageBox.Show(@"选择的文件格式不正确~,必须是*.xls|*.xlsx");
                return;
            }

            var sheet = workbook.GetSheetAt(0);
            ViewList_UpLogistics.Clear();
            for (var i = 1; i < sheet.LastRowNum + 1; i++)
            {
                var row = sheet.GetRow(i);

                ViewList_UpLogistics.AddItems(title =>
                {
                    var index = -1;
                    switch (title)
                    {
                        case "ID":
                            return (ViewList_UpLogistics.GetCount() + 1).ToString();
                        case "浏览器":
                            index = 0;
                            break;
                        case "订单编号":
                            index = 1;
                            break;
                        case "售后编号":
                            index = 2;
                            break;
                        case "物流单号":
                            index = 3;
                            break;
                    }

                    if (index == -1) return null;
                    return ExcelHelper.GetCellValue(row.GetCell(index));
                });
            }

            workbook.Dispose();
        }

        private void toolStripMenuItem12_Click(object sender, EventArgs e)
        {
            if (ViewList_Phone.GetSelectedItemFirstIndex() > -1)
            {
                ViewList_Phone.UpdateText(ViewList_Phone.GetSelectedItemFirstIndex(), "状态", "");
            }
        }

        /// <summary>
        /// 恢复Cookie
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {
            if (ViewList_Group.GetSelectedItemFirstIndex() > -1)
            {
                Task.Run(async () =>
                {
                    var Index = ViewList_Group.GetSelectedItemFirstIndex();
                    var PID = ViewList_Group.GetItemString(Index, "PID");
                    if (!string.IsNullOrEmpty(PID))
                    {
                        try
                        {
                            var p = Process.GetProcessById(int.Parse(PID));
                            Log("浏览器窗口已打开");
                            return;
                        }
                        catch (Exception)
                        {
                        }
                    }

                    var GroupModel = AppClass.Get_GroupModel(GetActivityGroup());
                    var Dev = await RunSingleItemChrome(GroupModel, Index,
                        (GroupItemModel)ViewList_Group.GetDataTag(Index));
                    if (Dev != null)
                    {
                        ViewList_Group.UpdateText(Index, "PID", Dev.ChromeProcess.Id.ToString());
                        await Dev.AutoSetCookies();
                        _chromeDrive = Dev;
                    }
                });
            }
        }


        private async Task<ChromeDrive> RunSingleItemChrome(GroupModel GM, int index, GroupItemModel IM)
        {
            var Dev = new ChromeDrive(Log, GM);
            try
            {
                var proxy = string.Empty;
                if (GM?.UseProxy == true)
                {
                    var proxies = GM.ProxyUrl.Split(",".ToCharArray(),
                        StringSplitOptions.RemoveEmptyEntries);
                    if (proxies.Length == 1)
                    {
                        proxy = proxies[0];
                    }
                    else
                    {
                        if (proxies.Length <= index)
                        {
                            Log("分组中的代理数量不足");
                            return default;
                        }

                        proxy = proxies[index];
                    }
                }

                if (await Dev.RunChromeProcessAsync(IM, proxy, GM.UseProxy))
                {
                    return Dev;
                }
            }
            catch (Exception ex)
            {
                Log("StartTry: " + ex.Message);
            }

            return null;
        }

        private void toolStripMenuItem14_Click(object sender, EventArgs e)
        {
            if (ViewList_Group.GetSelectedItemFirstIndex() > -1)
            {
                var Index = ViewList_Group.GetSelectedItemFirstIndex();
                var FileName = ViewList_Group.GetItemString(Index, "FileName");

                var m = (GroupItemModel)ViewList_Group.GetDataTag(Index);
                Log("账户文件:" + FileName + " 缓存:" + m.ChromeData);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (GetActivityGroup() != null)
            {
                var Name = GetActivityGroup();
                var m = AppClass.Get_GroupModel(Name);
                var F = new FormNewGroup(m);
                if (F.ShowDialog(this) == DialogResult.OK)
                {
                    if (F.GroupInfo.Title != Name)
                    {
                        if (!AppClass.GroupRenaming(Name, F.GroupInfo.Title))
                        {
                            MessageBox.Show("组重命名错误,当前编辑失败!");
                            return;
                        }
                    }

                    AppClass.Save_GroupModel(F.GroupInfo, F.GroupInfo.Title);
                    if (F.GroupInfo.Title != Name)
                    {
                        ReGroupList();
                        ReGroupItemViewList();
                    }
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (true)
            {
                panel1.Enabled = false;
                button1.Enabled = false;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var F = new FormDatabase();
            F.ShowDialog();
        }

        private void listView4_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == 0)
            {
                ViewList_UpLogistics.SetAllCheckState(listView4.Tag == null ? 1 : 0);
                if (listView4.Tag == null)
                {
                    listView4.Tag = "true";
                }
                else
                {
                    listView4.Tag = null;
                }
            }
        }

        private void listView3_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == 0)
            {
                ViewList_ReturnsGoods.SetAllCheckState(listView3.Tag == null ? 1 : 0);
                if (listView3.Tag == null)
                {
                    listView3.Tag = "true";
                }
                else
                {
                    listView3.Tag = null;
                }
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            Task.Run(async () =>
            {
                try
                {
                    Program._Run_ = 1;
                    // TestDev._Page_.MySelectorInputAndFocus("#as-input-as-mobile", "11110", true);
                    await _chromeDrive.PromotionReceive();
                }
                catch (Exception)
                {
                    // ignored
                }
            });
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            var Xx = new SmsApi();
            var Res = Xx.Login(textBox15.Text.Trim(), textBox16.Text.Trim());
            Log("API测试登陆:" + Res);
        }

        private void toolStripMenuItem15_Click(object sender, EventArgs e)
        {
        }

        private void toolStripMenuItem16_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认删除", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                Log("删除中耐心等待...");
                for (var i = ViewList_Group.GetCount() - 1; i >= 0; i--)
                {
                    if (!ViewList_Group.IsChecked(i))
                    {
                        continue;
                    }

                    var FileName = ViewList_Group.GetItemString(i, "FileName");
                    var GroupName = ViewList_Group.GetItemString(i, "GroupName");
                    Log("[删] " + ViewList_Group.GetItemString(i, "浏览器名称"));
                    if (AppClass.Del_GroupItem(GroupName, FileName))
                    {
                        ViewList_Group.RemoveItems(i);
                    }
                }

                Log("打勾删除完毕,如有残留代表文件被占用");
            }
        }

        private readonly object lockObj = new object();

        /// <summary>
        /// </summary>
        /// <param name="Index">1页数 3匹配数量 4日志</param>
        /// <param name="t"></param>
        private void CJ_SetStatusLabel(int Index, string t)
        {
            Invoke(new Action(() =>
            {
                lock (lockObj)
                {
                    statusStrip1.Items[Index].Text = t;
                }
            }));
        }

        #region 任务处理进程

        private async Task Task_Login(GroupModel group)
        {
            _ListPhoneIsEnd_ = false;
            var SApi = new SmsApi();
            await GroupSatrtItemChrome(async (index, Chrome) =>
            {
                if (radioButton1.Checked && _ListPhoneIsEnd_)
                {
                    Log("无手机号码可用!");
                    return false;
                }

                var IsLoginOk = false;
                if (radioButton1.Checked)
                {
                    //导入短信接收
                    var Api = new WebPhoneApi(GetListPhone);
                    if (Api.SetUrl(textBox10.Text))
                    {
                        var Res = await Chrome.Login(Api);
                        IsLoginOk = Res == "OK";
                        if (!IsLoginOk)
                        {
                            Log(Res);
                        }

                        if (Api.IndexItem > -1)
                        {
                            if (Res != "OK")
                            {
                                ViewList_Phone.UpdateText(Api.IndexItem, "状态", Res);
                            }

                            if (!Api.IsUse())
                            {
                                ViewList_Phone.UpdateText(Api.IndexItem, "状态", "");
                            }
                        }
                    }
                    else
                    {
                        Log("短信API地址错误");
                        Program._Run_ = -1;
                    }
                }
                else
                {
                    //API接收
                    if (!SApi.IsIsLogin)
                    {
                        for (var i = 0; i < 5; i++)
                        {
                            Log("登陆短信API");
                            var Res = SApi.Login(textBox15.Text.Trim(), textBox16.Text.Trim());
                            if (Res != "OK")
                            {
                                Log("登陆失败:" + Res + ",重试");
                            }
                            else
                            {
                                break;
                            }
                        }

                        if (!SApi.IsIsLogin)
                        {
                            Log("登陆失败过多,停止任务");
                            SetTaskSuccessFail(index, false);
                            return false;
                        }
                    }

                    var Res2 = await Chrome.Login(SApi);
                    IsLoginOk = Res2 == "OK";
                    if (Res2 != "OK")
                    {
                        Log(Res2);
                    }
                }

                if (IsLoginOk)
                {
                    if (checkBox1.Checked)
                    {
                        if (await Chrome.CheckExistOrder())
                        {
                            Log("判定老号!");
                            SetTaskSuccessFail(index, false);
                            return Program._Run_ == 1;
                        }
                    }

                    if (checkBox37.Checked)
                    {
                        if (!await Chrome.ClosePddWallet())
                        {
                            Log("关闭钱包失败!");
                            SetTaskSuccessFail(index, false);
                            return Program._Run_ == 1;
                        }
                    }

                    SetTaskSuccessFail(index, true);
                }
                else
                {
                    SetTaskSuccessFail(index, false);
                }

                if (radioButton1.Checked && _ListPhoneIsEnd_)
                {
                    Log("无手机号码可用!");
                    return false;
                }

                return Program._Run_ == 1;
            }, group);
        }

        private async Task Task_DownOrder(GroupModel group)
        {
            await GroupSatrtItemChrome(async (index, Chrome) =>
            {
                var Goods = GetGoodsCheckedRow();
                if (Goods == null)
                {
                    Log("商品列表已使用结束");
                    return false;
                }

                var info = new Dictionary<string, string>();

#if DEBUG
                info.Add("收货人", "守护");
                info.Add("电话", "18963238166");
                info.Add("省", "山东省");
                info.Add("市", "枣庄市");
                info.Add("区", "市中区");
                info.Add("详细地址", "三角花园大桥附近");
#else
                info.Add("收货人", (string)Goods["收货人"]);
                info.Add("电话", (string)Goods["电话"]);
                info.Add("省", (string)Goods["省"]);
                info.Add("市", (string)Goods["市"]);
                info.Add("区", (string)Goods["区"]);
                info.Add("详细地址", (string)Goods["详细地址"]);
                if (string.IsNullOrEmpty((string)info["收货人"]) || string.IsNullOrEmpty((string)info["电话"]))
                {
                    Log("商品ID:收货地址不全");
                    return false;
                }
#endif
                var Skus = Goods[DataGridHelpr._RowData_] as JArray;
                if (Skus == null || string.IsNullOrEmpty((string)Goods["下单Sku"]))
                {
                    Chrome.Log("商品ID:[" + Goods["商品ID"] + "]未选择Sku");
                    return false;
                }

                if (await Chrome.AddAddressTask(info))
                {
                    var OrderSkus = (string)Goods["下单Sku"];
                    var selectIndex = int.Parse(Regex.Match(OrderSkus, "\\[(\\d+?)\\]")?.Groups[1].Value ?? "0") - 1;
                    Debug.WriteLine("添加收货地址成功");
                    var Res = await Chrome.DownOrder((string)Goods["商品ID"],
                        ((JArray)Skus[selectIndex]["skus"]).Select(c => (string)c).ToArray());
                    if (Res != "OK")
                    {
                        Chrome.Log("下单失败:" + Res);
                        SetTaskSuccessFail(index, false);
                    }
                    else
                    {
                        //到达下单页面
                        if (await Chrome.OrderPayment(double.Parse((string)Skus[selectIndex]["price"])))
                        {
                            if (await Chrome.AlipayPayment(checkBox2.Checked, textBox6.Text.Trim(),
                                    textBox1.Text.Trim()))
                            {
                                Chrome.Log("下单成功");
                                SetTaskSuccessFail(index, true);
                                return true;
                            }
                        }
                        else
                        {
                            Chrome.Log("拼多多立即支付失败");
                        }

                        SetTaskSuccessFail(index, false);
                    }
                }
                else
                {
                    SetTaskSuccessFail(index, false);
                }

                return Program._Run_ == 1;
            }, group);

            // return await Chrome.Login();
        }

        private async Task Task_OrderExport(GroupModel group)
        {
            var SavePath = Path.Combine(DataPath,
                $"{group.Title}导出订单_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
            var MapCols =
                (Dictionary<string, string>)Invoke(new Func<Dictionary<string, string>>(GetOrderExportMapCols));
            var DtList = new DataTable();
            var Keys = MapCols.Keys.ToArray();
            for (var i = 0; i < MapCols.Count; i++)
            {
                DtList.Columns.Add(Keys[i]);
            }
            var OrderGoodsList = new List<OrderGoodsModel>();
            //-----------------------------------
            await GroupSatrtItemChrome(async (Index, Chrome) =>
            {
                var BrowserId = ViewList_Group.GetItemString(Index, "GroupName") + "-" +
                                ViewList_Group.GetItemString(Index, "浏览器名称") + "-" +
                                ViewList_Group.GetItemString(Index, "FileName");
                var OrderGoods = await Chrome.OrderExportTask();
                if (OrderGoods != null)
                {
                    SetTaskSuccessFail(Index, true);
                }

                if (OrderGoods == null)
                {
                    OrderGoods = new List<OrderGoodsModel>();
                    var m = new OrderGoodsModel();
                    m.BrowserID = BrowserId;
                    m.OrderStatus = "导出错误";
                    SetTaskSuccessFail(Index, false);
                    OrderGoods.Add(m);
                }
                else if (OrderGoods.Count == 0)
                {
                    var m = new OrderGoodsModel();
                    m.BrowserID = BrowserId;
                    m.OrderStatus = "未有订单列表";
                    OrderGoods.Add(m);
                }
                else
                {
                    foreach (var item in OrderGoods)
                    {
                        item.BrowserID = BrowserId;
                    }
                }

                var workbook = new XSSFWorkbook();
                Log("保存表格数据中...");
                DtList.Rows.Clear();
                OrderGoodsList.AddRange(OrderGoods);
                var sheet = workbook.CreateSheet("结果");
                var mapValues = MapCols.Values.ToArray();
                var mapKeys = MapCols.Keys.ToArray();
                {
                    var row = sheet.CreateRow(0);
                    for (var i = 0; i < mapKeys.Length; i++)
                    {
                        var cell = row.CreateCell(i); //在第二行中创建单元格
                        cell.SetCellValue(mapKeys[i]); //循环往第二行的单元格中添加数据
                    }
                }
                var _type_ = new OrderGoodsModel().GetType();
                for (var i = 0; i < OrderGoodsList.Count; i++)
                {
                    var row = sheet.CreateRow(i + 1);
                    for (var ii = 0; ii < mapValues.Length; ii++)
                    {
                        var P = _type_.GetProperty(mapValues[ii]);
                        var v = P.GetValue(OrderGoodsList[i])?.ToString() ?? string.Empty;
                        var cell = row.CreateCell(ii);
                        cell.SetCellValue(v);
                    }
                }

                ExcelHelper.AutoColumnWidth(sheet, mapKeys.Length);
                if (File.Exists(SavePath))
                {
                    File.Delete(SavePath);
                }

                using (var sw = File.OpenWrite(SavePath))
                {
                    workbook.Write(sw);
                }

                workbook.Dispose();
                return Program._Run_ == 1;
            }, group);
        }


        private void AutoColumnWidth(ISheet sheet, int cols)
        {
            for (var col = 0; col <= cols; col++)
            {
                sheet.AutoSizeColumn(col); //自适应宽度，但是其实还是比实际文本要宽
            }
        }

        private async Task Task_AfterSaleOrder(GroupModel group)
        {
            var SavePath = Path.Combine(DataPath, $"{group.Title}导出售后订单" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");

            var MapCols =
                (Dictionary<string, string>)Invoke(new Func<Dictionary<string, string>>(GetOrderAfterSalesMapCols));
            var DtList = new DataTable();
            var Keys = MapCols.Keys.ToArray();
            for (var i = 0; i < MapCols.Count; i++)
            {
                DtList.Columns.Add(Keys[i]);
            }

            var SaleModelsList = new List<AfterSaleModel>();


            //-----------------------------------
            await GroupSatrtItemChrome(async (Index, Chrome) =>
            {
                var BrowserID = ViewList_Group.GetItemString(Index, "GroupName") + "-" +
                                ViewList_Group.GetItemString(Index, "浏览器名称") + "-" +
                                ViewList_Group.GetItemString(Index, "FileName");

                var SaleModels = await Chrome.AfterSaleOrderTask();

                if (SaleModels != null)
                {
                    SetTaskSuccessFail(Index, true);
                }


                if (SaleModels == null)
                {
                    SaleModels = new List<AfterSaleModel>();
                    var m = new AfterSaleModel();
                    m.BrowserID = BrowserID;
                    m.OrderStatus = "导出错误";
                    SetTaskSuccessFail(Index, false);
                    SaleModels.Add(m);
                }
                else if (SaleModels.Count == 0)
                {
                    var m = new AfterSaleModel();
                    m.BrowserID = BrowserID;
                    m.OrderStatus = "未有订单列表";
                    SaleModels.Add(m);
                }
                else
                {
                    foreach (var item in SaleModels)
                    {
                        item.BrowserID = BrowserID;
                    }
                }

                var workbook = new XSSFWorkbook();
                Log("保存表格数据中...");
                DtList.Rows.Clear();
                SaleModelsList.AddRange(SaleModels);
                var sheet = workbook.CreateSheet("结果");
                var mapValues = MapCols.Values.ToArray();
                var mapKeys = MapCols.Keys.ToArray();
                {
                    var row = sheet.CreateRow(0);
                    for (var i = 0; i < mapKeys.Length; i++)
                    {
                        var cell = row.CreateCell(i); //在第二行中创建单元格
                        cell.SetCellValue(mapKeys[i]); //循环往第二行的单元格中添加数据
                    }
                }
                var _type_ = new AfterSaleModel().GetType();
                for (var i = 0; i < SaleModelsList.Count; i++)
                {
                    var row = sheet.CreateRow(i + 1);

                    for (var ii = 0; ii < mapValues.Length; ii++)
                    {
                        var P = _type_.GetProperty(mapValues[ii]);
                        var v = P.GetValue(SaleModelsList[i])?.ToString() ?? string.Empty;
                        var cell = row.CreateCell(ii);
                        cell.SetCellValue(v);
                    }
                }

                ExcelHelper.AutoColumnWidth(sheet, mapKeys.Length);
                if (File.Exists(SavePath))
                {
                    File.Delete(SavePath);
                }

                using (var sw = File.OpenWrite(SavePath))
                {
                    workbook.Write(sw);
                }

                workbook.Dispose();
                return Program._Run_ == 1;
            }, group);
        }

        private async Task<bool> Task_UploadOrderTracking(int Index, ChromeDrive Chrome)
        {
            var m = new UploadOrderTrackingModel();
            m.Directions = textBox7.Text;
            m.order_sn = ViewList_UpLogistics.GetItemString(Index, "订单编号");
            m.tracking = ViewList_UpLogistics.GetItemString(Index, "物流单号");
            m.salesId = ViewList_UpLogistics.GetItemString(Index, "售后编号");
            m.Freight = textBox8.Text.Trim();
            return await Chrome.UploadOrderTrackingTask(m);
        }

        private async Task<bool> Task_ReturnsGoods(int Index, ChromeDrive Chrome)
        {
            var m = new ReturnsGoodsInfoModel();
            m.IsRefunds = radioButton8.Checked;
            m.Phone = textBox9.Text;
            m.Reason = (string)Invoke(new Func<string>(() => comboBox2.Text));
            m.Directions = textBox5.Text;
            m.order_sn = ViewList_ReturnsGoods.GetItemString(Index, "订单编号");

            return await Chrome.ReturnsGoodsTask(m);
            //ReturnsGoodsInfoModel
        }

        #endregion 任务处理进程

        #region 导出表格生成器

        /// <summary>
        ///     生成导出订单表格字典
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, string> GetOrderExportMapCols()
        {
            var MapCols =
                "浏览器#BrowserID|订单编号#OrderSn|交易状态#OrderStatus|店铺名称#MallName|商品ID#GoodsId|商品名称#goodsName|属性SKU#SkuSpec|实际付款#OrderAmount|运费#Suffix|创建时间#CreateTime|发货时间#DeliveryTime|物流公司#CourierName|最新物流#LatestProgress|签收时间#SigningTime|物流状态#LogisticsStatus|运单号#CourierNumber|收货人姓名#ReceiveName|收货人电话#Mobile|省#ProvinceName|市#CityName|区县#DistrictName|详细地址#ShippingAddress";
            //List<string> Checkeds = new List<string>();
            // Checkeds.Add("浏览器");
            //foreach (Control item in tabPage5.Controls)
            //{
            //    CheckBox Box = item as CheckBox;
            //    if (Box != null && Box.Checked)
            //    {
            //        Checkeds.Add(Box.Text);
            //    }
            //}
            var CheckedMap = new Dictionary<string, string>();
            foreach (var item in MapCols.Split('|'))
            {
                var Name = item.Substring(0, item.IndexOf("#"));
                var _Field = item.Substring(item.IndexOf("#") + 1);

                CheckedMap.Add(Name, _Field);

                //if (Checkeds.Any(a => Name == a))
                //{

                //}
            }

            return CheckedMap;
        }

        /// <summary>
        ///     订单售后导出列
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, string> GetOrderAfterSalesMapCols()
        {
            var MapCols =
                "浏览器#BrowserID|订单编号#OrderSn|售后编号#afterSalesId|交易状态#OrderStatus|店铺名称#MallName|商品名称#goodsName|属性SKU#SkuSpec|实际付款#OrderAmount|申请时间#SqTime|退货地址#ReturnAddress";

            var CheckedMap = new Dictionary<string, string>();
            foreach (var item in MapCols.Split('|'))
            {
                var Name = item.Substring(0, item.IndexOf("#"));
                var _Field = item.Substring(item.IndexOf("#") + 1);
                CheckedMap.Add(Name, _Field);
            }

            return CheckedMap;
        }

        #endregion 导出表格生成器
    }
}